import { GlobalVariable } from '@/constans'
import axios, { type AxiosResponse, type InternalAxiosRequestConfig } from 'axios'
import { showToast } from 'vant'

const instance = axios.create({
  baseURL: GlobalVariable.BASE_URL,
  timeout: GlobalVariable.TIME_OUT,
})

instance.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 注入token
    // h5 调用鸿蒙端 获取token
    // window.hdm
    // window.hdm.getToken()
    // window.hdm
    // window.hdm.getToken()
    const token = window.hdm.getToken() // 获取sdk的token
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => Promise.reject(error),
)

instance.interceptors.response.use(
  (response: AxiosResponse) => {
    if (response.data.code === GlobalVariable.SUCCESS_CODE) {
      return response.data.result
    }
    showToast({
      message: response.data.message,
    })
    return Promise.reject(new Error(response.data.message))
  },
  (error) => Promise.reject(error),
)

export class RequestAxios {
  get<T>(url: string, params?: object) {
    return instance.get<null, T>(url, { params })
  }
  post<T>(url: string, data?: object) {
    return instance.post<null, T>(url, data)
  }
  put<T>(url: string, data?: object) {
    return instance.put<null, T>(url, data)
  }
  delete<T>(url: string, params?: object, data?: object) {
    return instance.delete<null, T>(url, { params, data })
  }
}
